import appConfig from '~/config/app.config'
import Stomp from '@stomp/stompjs'
import SockJS from 'sockjs-client'
import { MQ_TOPIC, MQ_MESSAGE} from './rabbitmq.service.config'
import { RabbitImportService } from './rabbit-import.service';

export class RabbitService {
    
    // 实例
    public static instance: RabbitService

    public static connect() {
        RabbitService.instance = new RabbitService()
    }

    public static disConnect() {
        return null
    }

    private client: any

    // RabbitService构造器
    constructor() {
        const rabbit: any = appConfig.rabbitmq
        if (rabbit.socket.startsWith('ws://') || rabbit.socket.startsWith('wss://')) {
            this.client = Stomp.client(rabbit.socket)
        } else {
            const ws = new SockJS(rabbit.socket)
            this.client = Stomp.over(ws)
        } 

        this.client.connect(
            rabbit.username,
            rabbit.password,
            this.onConnect.bind(this),
            this.onError.bind(this),
            this.onClose.bind(this),
            rabbit.vhost
        )
    } 

    private onConnect() {
        console.log('rabbitmq 连接成功!', Date.now())
        
        // 创建订阅者
        const rabbitImportService: RabbitImportService = new RabbitImportService()
        this.client.subscribe(`${MQ_TOPIC.MQ_TOPIC_EXCHANGE_KEEP}`, rabbitImportService.handleImport())
    }

    private onError() {
        console.log('rabbitmq 连接失败')
    }

    private onClose() {
        console.log('rabbitmq 连接关闭')
    }


}